/**
 * Created by tedi on 2018/3/20.
 各模块在自定义页面时会需要使用到控件
 */
odoo.define('lift_base.common_widget', function (require) {
"use strict";

    var core = require('web.core');
    var session = require('web.session');
    var form_common = require('web.form_common');
    var formats = require('web.formats');
    var Model = require('web.Model');
    var Widget = require('web.Widget');
    var FormView = require('web.FormView');
    var ListView = require("web.ListView");
    var WebClient = require('web.AbstractWebClient');

    var utils = require('web.utils');

    var _t = core._t;
    var QWeb = core.qweb;

    WebClient.include({
         init: function(parent) {
                this._super(parent);
                this.set('title_part', {"zopenerp": "天益"});
         },
        set_title_part: function(part, title) {
            var tmp = _.clone(this.get("title_part"));
            tmp[part] = title;
            if ('zopenerp' in tmp){
                tmp['zopenerp'] = '天益';
            }
            this.set("title_part", tmp);
        },
    });

    //通用消息盒子
    var CommonInfoBoxWidget = Widget.extend({
        template:"lift_base_common_info_box_template",
        events:{
            "click a.tyibs-common-info-box-button":"call_window_action"
        },
        init:function(parent, title, value, bg_color, fa_icon, res_model, domain, context){
            this._super(parent, arguments);
            this.title = title;
            this.value = value;
            this.bg_color = bg_color;
            this.fa_icon = fa_icon;
            this.res_model = res_model;
            this.domain = domain;
            this.context = context;
        },
        call_window_action:function(){
            var self = this;
            if(self.res_model==undefined){
                return false;
            }
            self.do_action({
                name: self.title,
                type: 'ir.actions.act_window',
                res_model: self.res_model,
                views: [[false, 'list'],[false, 'form']],
                target: 'current',
                domain: self.domain,
                context: self.context ? self.context : {},
            });
            return false;
        }
    });

    //带进度条的消息盒子控件，更漂亮
    var CommonInfoBoxWithProgressWidget = CommonInfoBoxWidget.extend({
        template: "lift_base_common_info_box_with_progressbar_template",
        init:function(parent, title, value, bg_color, fa_icon, res_model, domain, description, percent, context){
            this._super(parent, title, value, bg_color, fa_icon, res_model, domain, context);
            //this._super(parent, arguments);
            this.description = description;
            this.percent = percent;
        }
    });

    /*通用的地图显示控件，只显示位置信息*/
    var BaiduMapWidget = form_common.FormWidget.extend({
        template:"baidu_map_template",
        init: function(field_manager, node) {
            this._super(field_manager, node);
            this.la_field = node.attrs.la;
            this.ln_field = node.attrs.ln;
            this.res_model = node.attrs.res_model;
        },
        start: function () {
            this._super();
            this.field_manager.on("field_changed:"+this.la_field,this,this.show_baidu_map);
            this.field_manager.on("field_changed:"+this.ln_field, this, this.show_baidu_map);
            this.show_baidu_map();
        },
        show_baidu_map:function(){
            var ln = this.field_manager.get_field_value(this.ln_field);
            var la = this.field_manager.get_field_value(this.la_field);
            var self = this;
                var map = new BMap.Map(self.$el[0]);
                //var map = new BMap.Map(self.$("div.o_baidu_map"));
                var point = new BMap.Point(ln,la);
                // 如果没有坐标则显示为市中心
                if(la!=0 || ln!=0 ){
                    var marker = new BMap.Marker(point);
                    map.addOverlay(marker);
                    map.centerAndZoom(point, 15);
                }else{
                    map.centerAndZoom("无锡市", 15);
                }
                map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
        }
    });


    //列表中音频播放
    var ListColumn = core.list_widget_registry.get('field');
    var TyibsAudioColumn = ListColumn.extend({
        _format:function(row_data, options){
            var source_model = this.source_model;
            var source_field = this.source_field;
            if(row_data[this.id]!=undefined && (row_data.id!=undefined)){
                var value = row_data[this.id].value;
                if(value){
                    var record_id = row_data.id.value;
                    return _.template("<audio controlsList='nodownload' preload='none' class='tyibs_audio_column' controls='controls' src='/web/content?model=<%-model%>&field=<%-field%>&id=<%-id%>'></audio>")({
                        model: source_model,
                        field: source_field,
                        id: record_id
                    });
                }
            }
            return this._super(row_data,options);
        },
    });

    //列表中秒转换成时分秒
    var TimeSpanColumn = ListColumn.extend({
        _format:function(row_data, options){
            if(row_data[this.id]!=undefined && (row_data.id!=undefined)){
                var value = row_data[this.id].value;
                if(value){
                    return _.template("<span><%-time%></span>")({time: format_second_to_time(value)});
                }
            }
            return this._super(row_data,options);
        },
    });

    var format_second_to_time = function (total_seconds) {
        var hours = parseInt(total_seconds / 3600);
        var minutes = parseInt(total_seconds % 3600 / 60);
        var seconds = total_seconds % 3600 % 60;

        function switch_standard_time_number(number) {
            if (number > 9){
                return number.toString();
            }else if (number == 0){
                return "00";
            }else {
                return "0" + number.toString();
            }
        }
        return switch_standard_time_number(hours) + ":" + switch_standard_time_number(minutes) + ":" + switch_standard_time_number(seconds);
    };

    //binary图片预览
    var FormWidget = core.form_widget_registry.get('image');
    var ImageBinary = FormWidget.extend({
        render_value:function(){
            var url = this.placeholder;
            if(this.get('value')) {
                if(!utils.is_bin_size(this.get('value'))) {
                    url = 'data:image/png;base64,' + this.get('value');
                } else {
                    url = session.url('/web/image', {
                        model: this.view.dataset.model,
                        id: JSON.stringify(this.view.datarecord.id || null),
                        field: (this.options.preview_image)? this.options.preview_image : this.name,
                        unique: (this.view.datarecord.__last_update || '').replace(/[^0-9]/g, ''),
                    });
                }
            }

            var $img = $(QWeb.render("FieldBinaryImage-img", {widget: this, url: url}));

            var self = this;
            $img.click(function(e) {
                //预览图片，不能右键下载
                var img_page = window.open(url);
                img_page.document.write("<img src="+url+" style='max-width: 100%;max-height: 100%;'/>");
                if(self.view.get("actual_mode") == "view") {
                    var $button = $(".o_form_button_edit");
                    $button.openerpBounce();
                    e.stopPropagation();
                }
            });
            this.$('> img').remove();
            if (self.options.size) {
                $img.css("width", "" + self.options.size[0] + "px");
                $img.css("height", "" + self.options.size[1] + "px");
            }
            this.$el.prepend($img);
            $img.on('error', function() {
                self.on_clear();
                $img.attr('src', self.placeholder);
                self.do_warn(_t("Image"), _t("Could not display the selected image."));
            });
            // return this._super();
        },
    });

    //many2many图片预览
    var Many2manyBinary = core.form_widget_registry.get('many2many_binary');
    var FieldMany2ManyBinaryMultiFiles = Many2manyBinary.extend({
        get_file_url: function(attachment) {
            //将图片地址的donwload=true去掉就能实现简单的预览
            return '/web/content/' + attachment.id;
        },
    });

    // 地图选点更新坐标
    var BaiduMapChooseLocationWidget = form_common.FormWidget.extend({
        template:"baidu_map_template",
        init: function(field_manager, node) {
            this._super(field_manager, node);
        },
        start: function () {
            this._super();
            this.show_baidu_map();
        },
        show_baidu_map:function(){
            var ln = this.field_manager.get_field_value("ln");
            var la = this.field_manager.get_field_value("la");
            var self = this;
            //enableMapClick:底图可点功能，默认True是开启
            var map = new BMap.Map(self.$el[0],{enableMapClick: false});
            self.map = map;
            var point = new BMap.Point(ln,la);
            var marker = new BMap.Marker(point);
            map.addOverlay(marker);
            map.enableScrollWheelZoom(true);
            self.marker = marker;
            setTimeout(function () {
                if (ln == 0 || la == 0){
                    map.centerAndZoom("无锡市", 10);
                }else {
                    map.centerAndZoom(point, 15);
                }
                self.choose_location();
            }, 100);
        },
        choose_location: function () {
            var self =this;
            self.map.addEventListener("click", function(e){
                var pt = e.point;
                self.marker.setPosition(pt);
                self.map.panTo(pt);
                self.field_manager.set_values({ln:pt.lng,la:pt.lat});
                console.log(pt.lng,pt.lat);
            });
        }
    });

    var get_default_city = function (callback) {
        new Model("tyibs.base.province.city").query(['name','code']).filter([['is_default', '=', true]]).limit(1).all().then(function (res) {
            if (res.length > 0){
                // 有默认城市
                callback(res[0])
            }else {
                alert("未设置默认城市")
            }
       });
    };

    //不需要和具体的某个对象关联，调用方式如下：
    //<baidu_map_widget/>
    core.form_tag_registry.add('baidu_map_widget', BaiduMapWidget);
    core.form_tag_registry.add('baidu_map_choose_location_widget', BaiduMapChooseLocationWidget);
    core.list_widget_registry.add('field.tyibs_audio_column', TyibsAudioColumn);
    core.list_widget_registry.add('field.tyibs_time_span_column', TimeSpanColumn);
    core.form_widget_registry.add('tyibs_image_binary', ImageBinary);
    core.form_widget_registry.add('tyibs_many2many_binary', FieldMany2ManyBinaryMultiFiles);

    return {
        get_default_city: get_default_city,
        CommonInfoBoxWidget: CommonInfoBoxWidget,
        CommonInfoBoxWithProgressWidget: CommonInfoBoxWithProgressWidget,
    };
});
